package com.whccb.apps.office.document.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;

public class ModifyStatusAfterTaskComplateEvent extends ExecuteListener {

	public String getDescription() {
		return "公文发文流程，在相应节点更新流程状态。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public void execute(ProcessExecutionContext pec) throws Exception {
		handle(pec);
	}

	private void handle(ProcessExecutionContext pec) {
		String processDefId = pec.getProcessDef().getId();
		String bindid = pec.getProcessInstance().getId();
		String taskDefId = pec.getTaskInstance().getActivityDefId();
		String boName = "";
		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(bindid);
		if (paramMap != null && !paramMap.isEmpty()) {
			boName = paramMap.get("BONAME") != null ? paramMap.get("BONAME")
					.toString() : "";
		}

		String jsonStr = SDK.getRepositoryAPI().getActivityExtendAttribute(
				processDefId, taskDefId);
		List<String> checkMenuList = new ArrayList<String>();
		String taskStatus = "";
		if (StringUtils.isNotEmpty(jsonStr)) {
			JSONArray jsons = JSONArray.fromObject(jsonStr);
			if (jsons != null && !jsons.isEmpty() && jsons.size() > 0) {
				for (int i = 0; i < jsons.size(); i++) {
					JSONObject json = jsons.getJSONObject(i);
					if (json != null) {
						if (ODConstant.TASKSTATUSMENT.equals(json.get("key"))) {
							String valueStr = json.get("value").toString();
							String[] values = valueStr.split("-");
							if (values != null && values.length > 0) {
								for (String value : values) {
									if (StringUtils.isNotEmpty(value)) {
										checkMenuList.add(value);
									}
								}
							}
						}
						if (ODConstant.TASKSTATUS.equals(json.get("key"))) {
							taskStatus = json.get("value").toString();
						}
					}
				}
			}
		}

		if (checkMenuList != null && !checkMenuList.isEmpty()
				&& checkMenuList.size() > 0 && StringUtils.isNotEmpty(boName)) {
			for (String checkMenu : checkMenuList) {
				if (StringUtils.isNotEmpty(checkMenu)
						&& pec.isChoiceActionMenu(checkMenu)) {
					String updateSql = " UPDATE " + boName
							+ " SET STATUS = :STATUS WHERE BINDID =:BINDID ";
					Map<String, Object> updateParam = new HashMap<String, Object>();
					updateParam.put("STATUS", taskStatus);
					updateParam.put("BINDID", bindid);
					DBSql.update(updateSql, updateParam);
				}

			}
		}

	}
}
